const express = require('express');
let router = express.Router();

//日志
const {
    logger
} = require('../../config/logger');

const Response = require('../../utils/response')

//引入数据库连接池
const pool = require('../../config/mysql');
//引入数据库语句
const query = require('../../db/repairQuery/repairQuery')

//引入时间模块
const sd = require('silly-datetime');

//解析token
const {
    token_verify
} = require('../../config/jwt')

//解析from
const multiparty = require('multiparty')
//存储文件 
const path = require('path');
const fs = require('fs');

//发布维修信息
router.post('/publish', function (req, res) {
    const token = req.headers.authorization;
    const {
        userId
    } = token_verify(token); //发布者ID
    const ht = req.protocol; // 获取协议（http或者https）
    const host = req.headers.host; // 获取域名和端口号
    let form = new multiparty.Form({
        uploadDir: path.join(__dirname, '../../../public/images/repair')
    }) // 设置文件存储路径
    const time = sd.format(new Date(), 'YYYY-MM-DD HH:mm');
    form.parse(req, (err, msg, files) => {
        try {
            const type = msg['type'][0];
            const title = msg['title'][0];
            const describe = msg['describe'][0];
            const tel = msg['tel'][0];
            const image = files['image'][0]
            const newPath = form.uploadDir + "/" + image.originalFilename
            fs.renameSync(image.path, newPath)
            const url = ht + "://" + host + "/images/repair/" + image.originalFilename;
            pool.query(query.insert_repair, [userId, title, url, describe, tel, type, time], (error, result) => {
                if (error) {
                    logger().error("发布维修信息失败: " + error);
                    res.json(Response.error("发布维修信息失败", null));
                } else {
                    res.json(Response.success("发布维修信息成功", null));
                }
            });
        } catch (error) {
            logger().error("发布维修信息失败: " + error);
            res.json(Response.error("发布维修信息失败", null));
        }
    })
});

//获取个人的维修上报信息
router.get('/detailed', function (req, res) {
    const token = req.headers.authorization;
    const {
        userId
    } = token_verify(token); //查询ID
    pool.query(query.select_repair, userId, (error, result) => {
        if (error) {
            logger().error("获取我的报修信息失败: " + error);
            res.json(Response.error("获取我的报修信息失败", null));
        } else {
            const data = JSON.parse(JSON.stringify(result));
            res.json(Response.success("获取我的报修信息成功", data));
        }
    });
})

//删除我的维修信息
router.post('/delete', function (req, res) {
    const token = req.headers.authorization;
    const {
        userId
    } = token_verify(token); //请求删除者ID
    const repairId = req.body.repairId;
    pool.query(query.select_userId, repairId, (error, result) => {
        if (error) {
            logger().error("删除我的报修信息失败: " + error);
            res.json(Response.error("删除我的报修信息失败", null));
        } else {
            const {
                user_id
            } = JSON.parse(JSON.stringify(result[0]));
            if (userId == user_id) {
                pool.query(query.delete_repair, repairId, (error, result) => {
                    if (error) {
                        logger().error("删除我的报修信息失败: " + error);
                        res.json(Response.error("删除我的报修信息失败", null));
                    } else {
                        res.json(Response.success("删除我的报修信息成功", null));
                    }
                });
            } else {
                res.json(Response.error("删除我的报修信息失败", null));
            }
        }
    });
});

module.exports = router;